 <template>
  <!-- 页面-组织架构-新建部门 -->
  <div class="org-structure-wrap">
    <Form :model="formInfo" ref="deptForm" :rules="rules" :label-width="80">
      <!-- 部门编码 -->
      <Row :gutter="20" class="code-row-bg">
        <Col span="24">
          <Form-item :label="$t('module.orgManage.deptCode')" prop="orgCode">
            <Input
              placeholder
              v-model.trim="formInfo.orgCode"
              :disabled="orgInfo.newOrEdit == 'edit'"
            ></Input>
          </Form-item>
        </Col>
      </Row>
      <!-- 部门名称 -->
      <Row :gutter="20" class="code-row-bg">
        <Col span="24">
          <Form-item :label="$t('module.orgManage.deptName')" prop="orgName">
            <Input placeholder v-model.trim="formInfo.orgName" :maxlength="100"></Input>
          </Form-item>
        </Col>
      </Row>
      <!-- 排序号 -->
      <Row :gutter="20" class="code-row-bg">
        <Col span="24">
          <Form-item :label="$t('module.orgManage.sortId')" prop="orderNo">
            <InputNumber
              style="width:100%;"
              :min="0"
              :max="99"
              v-model="formInfo.orderNo"
              :placeholder="$t('module.orgManage.pleaseInput')"
            ></InputNumber>
          </Form-item>
        </Col>
      </Row>
      <!-- 状态 -->
      <Row :gutter="20" class="code-row-bg">
        <Col span="24">
          <Form-item :label="$t('common.status')" prop="status">
            <RadioGroup v-model="formInfo.enabled">
              <Radio :label="1">{{ $t("common.valid") }}</Radio>
              <Radio :label="0">{{ $t("common.invalid") }}</Radio>
            </RadioGroup>
          </Form-item>
        </Col>
      </Row>
      <!-- 描述 -->
      <Row :gutter="20" class="code-row-bg">
        <Col span="24">
          <Form-item :label="$t('module.orgManage.orgDesc')" prop="orgDesc">
            <Input
              placeholder
              type="textarea"
              :rows="4"
              :maxlength="1000"
              v-model="formInfo.orgDesc"
            ></Input>
          </Form-item>
        </Col>
      </Row>
      <!-- 拓展属性-模板- -->
      <!-- <Row v-if="!isShowTemplate" :gutter="20" class="code-row-bg">
        <p class="extendedAttrTitle">{{extendedAttrTitle}}</p>
        <Col span="24">
          <Form-item :label="$t('module.orgManage.template')" prop="template">
            <Select
              @on-change="changeSelect"
              v-model="formInfo.attributeContext"
              class="no-borderColor"
            >
              <Option
                v-for="(item,index) in dapartTemplateList"
                :key="index"
                :value="item.id"
              >{{item.templateName}}</Option>
            </Select>
          </Form-item>
        </Col>
      </Row>-->
    </Form>
    <div v-if="!isShowTemplate" class="extendClass">
      <p class="extendedAttrTitle">{{extendedAttrTitle}}</p>
      <span style="font-size:14px;padding-right:9px;">{{$t('module.orgManage.template')}}</span>
      <Select
        style="width:40%"
        @on-change="changeSelect"
        v-model="formInfo.attributeContext"
        class="no-borderColor"
      >
        <Option
          v-for="(item,index) in dapartTemplateList"
          :key="index"
          :value="item.id"
          :style="{ color:item.status == 2?'#bcbcbc!important': '' }"
        >{{item.templateName}}</Option>
        <!-- <Option v-for="(item,index) in dapartTemplateList" :key="index" :value="item.id">
          <span :style="item.status == 2?'color:#bcbcbc':''">{{item.templateName}}</span>
        </Option>-->
      </Select>
      <div
        class="assign-tree-dimension"
        ref="treeRoot"
        v-if="formInfo.attributeContext && isHintShow"
      >
        <span
          class="operation-hint"
          style="margin-left: 0;"
        >{{ $t("module.treeManage.templateNull") }}</span>
      </div>
      <form-create
        v-if="isShow"
        v-model="fcApi"
        :rule="ruleData"
        :option="option"
        class="extend-attr-create-formstyle"
      ></form-create>
    </div>
    <!-- <form-create
      v-if="isShow"
      v-model="fcApi"
      :rule="ruleData"
      :option="option"
      class="extend-attr-create-formstyle"
    ></form-create>-->
    <!-- <form-create></form-create> -->
  </div>
</template>

<script>
import { addDept, updateDept } from "@/api/orgApi.js";
import locales from "../locales.js";
import { getDepartmentTemplateList, templateDetail } from "@/api/extendAttrApi.js";
export default {
  mixins: [locales],
  components: {},
  props: {
    orgInfo: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    // 部门编码
    const validateOrgCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("module.orgManage.enterDepartmentalCode")));
      } else if (value.length > 30) {
        callback(new Error(this.$t("common.warning.codeCheckLength")));
      } else if (!new RegExp("^([a-zA-Z0-9]|_|-|\\.)+$").test(value)) {
        callback(new Error(this.$t("module.orgManage.codeContain")));
      } else if (new RegExp("[\u4e00-\u9fa5]").test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      }
      callback();
    };
    // 部门名称
    const validateOrgName = (rule, value, callback) => {
      if (value != value.trim()) {
        callback(new Error(this.$t("module.orgManage.noBalnk")));
      } else if (value.length > 100) {
        callback(new Error(this.$t("module.orgManage.nameMaxFifty")));
      }
      callback();
    };
    // 部门描述
    const validateOrgDesc = (rule, value, callback) => {
      if (value != null && value != value.trim() && value.trim() === "") {
        callback(new Error(this.$t("module.orgManage.enterLegalDesc")));
      }
      if (value != null && value.length > 1000) {
        callback(new Error(this.$t("module.orgManage.descMaxTH")));
      }
      callback();
    };
    return {
      formInfo: {
        orgCode: "", //部门编码
        orgName: "", //部门名称
        orgPath: this.orgInfo.orgPath + "/", //部门路径
        orderNo: 1, //排序号
        enabled: 1, //状态
        orgDesc: "", //描述
        parentType: this.orgInfo.idx == "org" ? 1 : 2, // 1代表在组织下新建根部门 2代表在根部门下新建子部门
        orgType: 10, // 0 类型为组织的公司 1 类型为组织的集团 10类型为部门 用于后端区分在组织树节点下展示组织节点而不包括部门节点
        tenantCode: this.orgInfo.tenantCode, //租户编码
        currentOrgId: this.orgInfo.currentOrgId, //组织id
        parentId: this.orgInfo.parentId, //选中的组织id或部门id
        attributeContext: ""
      },
      dapartTemplateList: [],
      isShow: false,
      isHintShow: false,
      isShowTemplate: false,
      ruleList: [],
      fcApi: null,
      // 字段规则
      rules: {
        orgCode: [{ validator: validateOrgCode, trigger: "blur", required: true }],
        orgName: [{ validator: validateOrgName, trigger: "blur", required: true }],
        orderNo: [{ required: true }],
        orgDesc: [{ validator: validateOrgDesc, trigger: "blur" }]
      },
      actions: [
        {
          text: this.$t("common.save"),
          theme: "primary",
          handle: () => {
            this.onOk();
          },
          loading: false
        },
        {
          text: this.$t("common.close"),
          handle: () => {
            this.$emit("Close");
          }
        }
      ]
    };
  },
  created: function() {
    if (this.orgInfo.newOrEdit == "edit") {
      this.$emit("SetTitle", this.$t("module.orgManage.editDept"));
      const _orgInfo = this.orgInfo.row;
      this.formInfo = {
        orgCode: _orgInfo.orgCode, //部门编码
        orgName: _orgInfo.orgName, //部门名称
        orderNo: _orgInfo.orderNo, //排序号
        enabled: _orgInfo.enabled, //状态
        orgDesc: _orgInfo.orgDesc, //描述
        orgId: _orgInfo.orgId,
        attributeContext: _orgInfo.attributeContext,
        currentOrgId: this.orgInfo.currentOrgId //组织id
        // parentType: 1, // 1代表在组织下新建根部门 2代表在部门下新建子部门
        // orgType: 10, // 0 类型为组织的公司 1 类型为组织的集团 10类型为部门 用于后端区分在组织树节点下展示组织节点而不包括部门节点
        // tenantCode: "" //租户编码
      };
      this.ruleList = _orgInfo.attributeValue ? _orgInfo.attributeValue.template : [];
      this.isShow = true;
    } else {
      this.$emit("SetTitle", this.$t("module.orgManage.newDept"));
    }

    this.$emit("SetPageWidth", 600);
    this.$emit("SetPageActions", this.actions);
    this.getDepartmentTemplate([1]);
  },
  computed: {
    extendedAttrTitle: function() {
      return this.$t("module.orgManage.extendedAttr");
    },
    ruleData() {
      return this.ruleList;
    },
    option() {
      return {
        resetBtn: false,
        submitBtn: false,
        form: {
          labelWidth: 100,
          size: "default"
        }
      };
    }
  },
  methods: {
    //   获取部门模板列表
    // 获取公司模板数据
    getDepartmentTemplate(statusList) {
      getDepartmentTemplateList(statusList).then(res => {
        if (res.data.length == 0) {
          this.isShowTemplate = true;
          return;
        } else {
          this.isShowTemplate = false;
        }
        this.dapartTemplateList = res.data;
        // 获取已归档模板（意义相当于选择以后被无效的模板）
        this.templateDetail(this.formInfo.attributeContext, "pigeonhole");
      });
    },
    onOk() {
      this.formInfo.attributeValue = {
        template: this.ruleData
      };
      const newFormData = {};
      if (this?.fcApi?.formData) {
        const formData = this.fcApi.formData();
        const rules = this.fcApi.rule;
        for (const r of rules) {
          newFormData[r.matchColumn] = r.type === 'checkbox'
            ? JSON.stringify(formData[r.field])
            : formData[r.field];
        }
      }
      const requestParams = {
        ...this.formInfo,
        ...newFormData
      }
      this.$refs["deptForm"].validate(valid => {
        if (valid) {
          this.actions[0].loading = true;
          if (this.orgInfo.newOrEdit == "edit") {
            updateDept(requestParams)
              .then(data => {
                this.$message.success({
                  content: this.$t("module.orgManage.editSuccess"),
                  duration: 3
                });
                this.modal = false;
                // this.$emit("Close", true);
                // 把数据传回页面
                let params = {
                  // data: this.formInfo,
                  data: requestParams,
                  newOrEdit: "edit"
                };
                this.$emit("Close", params);
              })
              .catch(data => {
                this.actions[0].loading = false;
              });
          } else {
            // 组织路径
            this.formInfo.orgPath += this.formInfo.orgCode;
            addDept(requestParams)
              .then(data => {
                this.loading = false;
                this.$message.success({
                  content: this.$t("module.orgManage.addDeparment"),
                  duration: 3
                });
                this.modal = false;
                // this.$emit("Close", data.data);
                // this.formInfo.orgId = data.data;
                // 把数据传回页面
                let params = {
                  // data: this.formInfo,
                  newOrEdit: "new"
                };
                this.$emit("Close", params);
              })
              .catch(data => {
                this.actions[0].loading = false;
              });
          }
        } else {
          this.$message.error(this.$t("common.formValidateFailed"));
        }
      });
    },
    // // 切换模板
    // changeSelect(val) {
    //   templateDetail(val).then(res => {
    //     this.ruleList = res.data.attributeContent.template;
    //     this.isShow = true;
    //   });
    // }
    // 切换模板
    changeSelect(val) {
      console.log(val);
      this.templateDetail(val, "changeSelect");
    },
    // 获取模板详情
    templateDetail(val, sign) {
      templateDetail(val).then(res => {
        if (sign == "pigeonhole") {
          const arr = [...this.dapartTemplateList, res.data || {}];
          const obj = {};
          this.dapartTemplateList = arr.filter(d => {
            if (d.id && !obj[d.id]) {
              obj[d.id] = true;
              return true;
            }
          });
          const _orgInfo = this.orgInfo.row
          const templateList = res?.data?.attributeContent?.template || []
          this.ruleList = templateList.map(t => {
            const item = {
              ...t,
              value: t.type === 'checkbox' && t?.matchColumn
                ? _orgInfo?.[t?.matchColumn]
                  ? JSON.parse(_orgInfo?.[t?.matchColumn])
                  : []
                : _orgInfo?.[t?.matchColumn] || ''
            }
            return item
          })
        } else {
          this.ruleList = res.data.attributeContent.template;
          this.isShow = true;
          this.isHintShow = this.ruleList.length == 0;
        }
      });
    }
  }
};
</script>
<style lang="less">
.extendedAttrTitle {
  font-size: 14px;
  font-weight: bold;
  border-bottom: 0 !important;
  line-height: 14px !important;
  margin-bottom: 20px;
}

.org-structure-wrap {
  // 选择拓展属性模板生成的表单
  .extend-attr-create-formstyle {
    margin-top: 20px;
    padding: 0;
    .ivu-form-item {
      display: flex;
      justify-content: space-between;
      .ivu-form-item-label {
        width: auto !important;
        min-width: 69px !important;
        max-width: 188px !important;
      }
      .ivu-form-item-content {
        margin-left: 0 !important;
        flex: 1;
        .ivu-input-number {
          width: 100% !important;
        }
      }
    }
  }
}
.extendClass {
  border: 1px solid #eee;
  padding: 20px;
  margin-left: 0 !important;
}
</style>